/**
 * Created by chenzp on 18-7-27.
 */
layui.use(['jquery', 'layer', 'table', 'form', 'ly', 'utl'], function () {

    var $ = layui.$
    var utl = layui.utl

    var charaterSctrip = {


        $aform: $('#aForm')
        , $sform: $('#sForm')

        , $htmlB: $('#htmlBlock')


        , url: {
            add: '/analyzer/character/add'
            , list: '/analyzer/character/list'
            , id: function (id) {
                return `/analyzer/character/${id}`
            }
        }

        , init: function () {


            $('#a_c_a_btn').openLy('a_c_a_from', 'click', {area: '700*500', title: '新增'})

            this.initTable()
            this.initSel()
            this.initEvent()
            this.submitForm()
        }

        , initEvent: function () {
            var $this = this
            layui.form.on('select(typeName)', function (data) {
                var index = data.elem.selectedIndex
                $this.selectedIndex = index
                $('.block-model').hide()
                if (index > 0) {
                    $('.block-model').eq(index - 1).show()
                }
            })

            //搜索表单
            this.$sform.find('button.btn-search').on('click', function () {
                $this.reloadTable(true)
            })


            //监听table工具事件
            layui.table.on('tool(a_c_table)', function (obj) {
                var data = obj.data
                if (obj.event === 'del') {
                    layer.confirm('确定删除？', function (index) {
                        layer.close(index)
                        utl.ajax($this.url.id(data.id),
                            {
                                type: 'delete'
                                , callback: function (res) {
                                $this.reloadTable(false)
                            }
                            })


                    });
                } else if (obj.event === 'edit') {
                    var $tr = $(obj.tr[0])
                    $tr.openLy('a_c_a_from', null, {area: '700*500', title: '编辑'})
                    $this.rewriteForm(data)
                }
            })


        }

        , initTable: function () {

            this.table = layui.table.render({
                elem: '#a_c_table'
                , url: this.url.list
                , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                , page: true //开启分页
                , loading: true//是否显示加载条
                , where: utl.serializeJson(this.$sform)
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {field: 'id', title: 'ID', sort: true}
                        , {field: 'name', title: '名称'}
                        , {
                        field: 'characterType', title: '类型', sort: true, templet: function (d) {
                            return d.characterType == 'html_strip' ? 'HTML过滤器' : d.characterType == 'mapping' ? 'mappings过滤器' : '正则过滤器'
                        }
                    }
                        , {field: 'value', title: '值'}
                        , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 115}
                    ]

                ]

            })
        }

        //初始化下拉框
        , initSel: function () {

            var $this = this
            var $block = $('.block-model')

            //html标签
            $block.eq(0).find('input').on('focusout', function () {
                var $btn = $this.addHtmlBtnStore($(this).val())
                if (!$btn) return
                $(this).before($btn)[0].focus()
                $(this).val('')
            })

            //mapping标签
            $block.eq(0).find('.html-add-btn').on('click', function () {
                var $btn = $this.addHtmlBtnStore($(this).prev().val())
                if (!$btn) return
                $(this).prev().before($btn).val('')
            })

            //替换字符
            $block.eq(1).find('button').on('click', function () {
                var html_rep = `<div class="row" style="height: 37px;">
                    <input type="text"  autocomplete="off" placeholder="原值"
                           class="layui-input mapping-tag">
                    <span class="mapping-tag">=></span>
                    <input type="text"  autocomplete="off" placeholder="新值"
                           class="layui-input mapping-tag">
                   <button type="button" class="layui-btn layui-btn-sm" style="margin-left: 20px;">―</button>
                </div>`

                var $html = $(html_rep)

                $html.find('input:eq(0)').on('focusout', function () {
                    $this.mappingStore = $this.mappingStore ? $this.mappingStore : []
                    var val = $(this).val().trim()
                    if (!val) {
                        layer.msg('值不能为空')
                        return
                    }

                    if ($.inArray(val, $this.mappingStore) != -1) {
                        layer.msg('存在一样的值')
                        $(this).val('')
                        $(this)[0].focus()
                        return
                    }

                    $this.mappingStore.push(val)
                })

                $html.find('button').on('click', function () {
                    $html.remove()
                })

                $(this).parent().before($html)
            })

        }

        //添加html标签
        , addHtmlBtnStore: function (value) {
            if (!value.trim()) {
                layer.msg('输入值不能为空')
                return false
            }
            this.htmlStore = this.htmlStore ? this.htmlStore : []

            if ($.inArray(value.trim(), this.htmlStore) != -1) {
                layer.msg('存在相同值')
                return false
            }

            this.htmlStore.push(value.trim())

            var $btn = $(`<button type="button" class="layui-btn layui-btn-sm html-tag">${value.trim()}<b>x</b></button>`)

            var $this = this
            $btn.find('b').on('click', function () {
                $this.htmlStore.splice($.inArray($(this).html().trim(), $this.htmlStore), 1);
                $btn.remove()
            })

            return $btn
        }

        //提交表单
        , submitForm: function () {

            var $this = this
            layui.form.on('submit(a-form)', function (data) {

                var characterVal = $this.characterVal()
                $.extend(data.field, {value: characterVal})
                utl.ajax($this.url.add, {
                    data: data.field
                    , callback: function (res) {
                        //重新加载渲染表格
                        $this.reloadTable(true)
                        layui.ly.close()
                        $this.resetForm()
                    }
                })
                return false;
            })
        }

        //获取不同类型选中的值
        , characterVal: function () {
            var index = this.selectedIndex ? this.selectedIndex : 0

            if (index == 0) return ''

            var $model = $('.block-model').eq(index - 1)

            if (index == 1) {
                var val = []
                for (var i = 0; i < $model.find('button').length; i++) {

                    var $btn = $model.find('button').eq(i).clone()
                    $btn.find('b').remove()
                    val.push($btn.text())
                }

                return JSON.stringify(val)

            } else if (index == 2) {

                var val = []
                for (var i = 0; i < $model.find('div.row').length; i++) {
                    var $row = $model.find('div.row').eq(i)
                    if ($row.find('input').length != 2) {
                        continue
                    }

                    var oldVal = $row.find('input').eq(0).val()
                    var newVal = $row.find('input').eq(1).val()
                    val.push(`${oldVal} => ${newVal}`)
                }

                return JSON.stringify(val)

            } else {
                return $model.find('input').val().trim()
            }
        }

        //重新载入表格数据
        , reloadTable: function (reset) {
            var paging = new Object()
            paging = reset ? {page: 1} : {}
            this.table.reload({
                where: utl.serializeJson(this.$sform)
                , page: paging
            })
        }

        //回写表单
        ,rewriteForm:function (data) {

            this.resetForm()

            layui.form.val('a_c_form',data)

            var $select = this.$aform.find('select')


            var index = $select.find('option:selected').index()

            $select.next().find('dl>dd').eq(index).trigger('click')

            var arrVal = JSON.parse(data.value)

            if(!arrVal) return

            var $models = this.$aform.find('.block-model')


            if(index == 3) {
                $models.eq(2).find('input').val(arrVal)
                return
            }

            for(var i=0;i<arrVal.length;i++) {
                var ele = arrVal[i]
                if (index == 1) {
                    $models.eq(0).find('input').val(ele).find('b').trigger('click')
                } else if (index == 2) {
                    var arrEle = ele.split('=>')
                    $models.eq(1).find('button:last').trigger('click').parent().prev().find('input:eq(0)').val(arrEle[0].trim()).parent().find('input:eq(1)').val(arrEle[1].trim())
                }
            }
        }

        //重置表单
        ,resetForm:function () {
            this.$aform.find('input[name]').val('')
            var $select = this.$aform.find('select')
            $select.next().find('dl>dd').eq(0).trigger('click')

            //清空表单下拉框缓存的值
            var $models = this.$aform.find('.block-model')
            $models.eq(0).find('button>b').trigger('click')

            var $row = $models.eq(1).find('.row')
            for(var i=0;i<$row.length;i++) {
                if($row.eq(i).find('input').length == 0 ) continue
                $row.eq(i).find('button').trigger('click')
            }

            $models.eq(2).find('input').val('')
        }
    }

    charaterSctrip.init()
})
